package com.vichat.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.vichat.common.cache.LocalCacher;
import com.vichat.common.constant.I18nConstant;
import com.vichat.common.exception.ViChatException;
import com.vichat.common.util.I18NUtil;
import com.vichat.common.util.NumberUtils;
import com.vichat.common.vo.Grid;
import com.vichat.common.vo.Json;
import com.vichat.common.vo.PageFilter;
import com.vichat.common.vo.ZTree;
import com.vichat.user.entity.SecFunction;
import com.vichat.user.entity.SecRole;
import com.vichat.user.entity.UserBasic;
import com.vichat.user.service.ISecService;
import com.vichat.user.vo.Privilege;
import com.vichat.user.vo.PrivilegeVO;
import com.vichat.user.vo.RoleMenuVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


@Controller
@RequestMapping("/vcapi/sec")
public class SecController extends BaseController {
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    private ISecService secService;

    /**
     * saveOrUpdSecFunc
     * 菜单管理
     *
     * @return
     */
    @RequestMapping("/secFunctionManagement")
    public String secFunctionManagement() {
        return "/sec/SecFunctionManagement";
    }

    /**
     * 角色管理
     *
     * @return
     */
    @RequestMapping("/secRoleManagement")
    public String secRoleManagement() {
        return "/sec/SecRoleManagement";
    }


    /**
     * 根据条件查询角色信息
     *
     * @param queryBean
     * @return
     */
    @RequestMapping("/querySecRole")
    @ResponseBody
    public Grid querySecRole(SecRole queryBean, PageFilter pf) {
        Grid grid = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();
            if (sessionUser != null) {
                queryBean.setPartyId(sessionUser.getPartyId());
            }
            if (StringUtils.isNotBlank(queryBean.getRoleName())) {
                queryBean.setRoleName(URLDecoder.decode(queryBean.getRoleName(), "UTF-8"));
                if (queryBean.getRoleName().indexOf("_") >= 0) {
                    queryBean.setRoleName(queryBean.getRoleName().replaceAll("_", "\\\\_"));
                }
            }
            List<SecRole> secRoles = secService.querySecRole(queryBean, pf);
            long count = secService.countSecRole(queryBean);
            grid.setData(secRoles);
            grid.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 保存或修改角色
     *
     * @param secRole
     * @return
     */
    @RequestMapping("/saveOrUpdSecRole")
    @ResponseBody
    public Json saveOrUpdSecRole(SecRole secRole) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            if (sessionUser != null && NumberUtils.isNotNullOrZero(sessionUser.getPartyId())) {
                secRole.setPartyId(sessionUser.getPartyId());
            }
            boolean result = secService.repeatSecRole(secRole);
            if (result) {
                if (!NumberUtils.isNotNullOrZero(secRole.getRoid()) || secRole.getRoid() != 1L) {//roid为空 或 roid不等于超级管理员
                    secRole.setRoleName(URLDecoder.decode(secRole.getRoleName(), "UTF-8"));
                    secService.saveOrUpdSecRole(secRole);
                    LocalCacher.refresh("SEC_ROLE");
                }
                json.setSuccess(true);
            } else {
//                json.setMsg("角色名重复");
//                json.setSuccess(false);
                String errorMsg = I18NUtil.getMessage("SecController.saveOrUpdSecRole.error_nameRepeat", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_nameRepeat, errorMsg);
            }
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 根据角色编号查询编号信息
     *
     * @param roid
     * @return
     */
    @RequestMapping("/getSecRoleByRoid")
    @ResponseBody
    public Json getSecRoleByRoid(Long roid) {
        Json json = new Json();
        try {
            SecRole secRole = secService.querySecRoleByRoid(roid);
            json.setObj(secRole);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 根据角色编号删除角色
     *
     * @param roid
     * @return
     */
    @RequestMapping("/delSecRole")
    @ResponseBody
    public Json delSecRole(Long roid) {
        Json json = new Json();
        try {
            if (roid != 1) {//不能删除超级管理员
                secService.delSecRole(roid);
                LocalCacher.refresh();
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 获取菜单树（两级）
     *
     * @return
     */
    @RequestMapping("/secZTree")
    @ResponseBody
    public Json secZTree() {
        Json json = new Json();
        List<ZTree> list = getSecZtreeList();
        json.setObj(list);
        return json;
    }

    /**
     * 菜单树（两级）
     *
     * @return
     */
    private List<ZTree> getSecZtreeList() {
        List<ZTree> list = new ArrayList<ZTree>();
        List<SecFunction> secFuncs = secService.querySecFunction();
        for (SecFunction sec : secFuncs) {
            ZTree tree = new ZTree();
            tree.setId(Long.parseLong(sec.getFid().toString()));
            tree.setName(sec.getFuncName());
            tree.setLevel(sec.getFuncLevel());
            if (sec.getParentFid() != null && sec.getParentFid().longValue() > 0) {
                tree.setpId(sec.getParentFid());
                tree.setParent(true);
            } else {
                tree.setParent(false);
            }
            tree.setOpen(true);
            list.add(tree);
        }
        return list;
    }

    /**
     * 获取菜单树
     *
     * @return
     */
    @RequestMapping("/secZTreeLevel")
    @ResponseBody
    public List<ZTree> secZTreeLevel(Long funLevel) {
        List<ZTree> list = new ArrayList<ZTree>();
        List<SecFunction> secFuncs = secService.getMenus(funLevel, null);
        for (SecFunction sec : secFuncs) {
            ZTree tree = new ZTree();
            tree.setId(Long.parseLong(sec.getFid().toString()));
            tree.setName(sec.getFuncName());
            tree.setOpen(true);
            list.add(tree);
        }
        return list;
    }

    /**
     * 查询菜单信息
     *
     * @param queryBean
     * @param pf
     * @return
     */
    @RequestMapping("/querySecFunction")
    @ResponseBody
    public Grid querySecFunction(SecFunction queryBean, PageFilter pf) {
        Grid grid = new Grid();
        try {
            pf.setRows(pf.getLimit());
            if (StringUtils.isNotBlank(queryBean.getFuncName()))
                queryBean.setFuncName(URLDecoder.decode(queryBean.getFuncName(), "UTF-8"));
            List<SecFunction> secFuncs = secService.querySecFunction(queryBean, pf);
            if (!secFuncs.isEmpty()) {
                for (SecFunction secFunction : secFuncs) {
                    if (NumberUtils.isNotNullOrZero(secFunction.getParentFid())) {
                        SecFunction secFunctionFDB = secService.querySecFuncByFid(secFunction.getParentFid());
                        secFunction.setParentName(secFunctionFDB.getFuncName());
                    }
                }
            }
            long count = secService.countSecFunction(queryBean);
            grid.setData(secFuncs);
            grid.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 根据角色编号查询菜单
     *
     * @return
     */
    @RequestMapping("/querySecPrivilege")
    @ResponseBody
    public String querySecPrivilege() {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            if (sessionUser != null) {
                if (sessionUser.getUserType() != 4) {
                    if (NumberUtils.isNotNullOrZero(sessionUser.getUid())) {
                        List<PrivilegeVO> privilegeVOS = secService.querySecPrivilege(sessionUser.getUid(),1);
                        return JSONObject.toJSONString(privilegeVOS);
                    }
                } else {
                    List<PrivilegeVO> privilegeVOS = secService.querySecPrivilege(sessionUser.getUid(),10);

                    return JSONObject.toJSONString(privilegeVOS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return "";
    }

    /**
     * 根据用户编号查询菜单分配信息
     *
     * @param uid
     * @return
     */
    @RequestMapping("/querySecRoleFunctionByUid")
    @ResponseBody
    public Json querySecRoleFunctionByUid(Long uid) {
        Json json = new Json();
        try {
            List<SecFunction> secRoleFuncVOS = secService.querySecRoleFuncVOByUid(uid);
            List<SecFunction> secRoleFuncVOToApp = secService.querySecRoleFuncVOByUidToApp(uid);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("secRoleWebFunc",secRoleFuncVOS);
            jsonObject.put("secRoleAppFunc",secRoleFuncVOToApp);
            json.setObj(jsonObject);
            json.setSuccess(true);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 根据角色编号查询菜单分配信息
     *
     * @param roid
     * @return
     */
    @RequestMapping("/querySecRoleFunctionByRoid")
    @ResponseBody
    public Json querySecRoleFunctionByRoid(Long roid) {
        Json json = new Json();
        try {
            List<SecFunction> secRoleFuncVOS = secService.querySecRoleFuncVOByRoid(roid);
            json.setObj(secRoleFuncVOS);
            json.setSuccess(true);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * @param
     * @return
     * @throws
     * @Title: saveSecRoleFunction
     * @Description: 角色分配菜单权限修改
     */
    @RequestMapping("/saveSecRoleFunction")
    @ResponseBody
    public Json saveSecRoleFunction(@RequestBody RoleMenuVO roleMenuVO) {
        Json json = new Json();
        try {
            secService.saveSecRoleFunction(roleMenuVO);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

}
